#pragma once
#include<iostream>
#include<pthread.h>
#include<queue>
#include<vector>
#include<string>
#include"Task.hpp"


#define num 3

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template<class T>
class ThreadPool
{
public:
    ThreadPool(int nums = num)
        :threadpool(nums)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }

    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }

    void Sleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

    void Wake()
    {
        pthread_cond_signal(&cond_);
    }

    std::string GetThreadName(pthread_t tid)
    {
        for (const auto& ti : threadpool)
        {
            if (ti.tid == tid)
                return ti.name;
        }
        return "None";
    }

    static void* handler(void* args)
    {
        ThreadPool<T>* tp = (ThreadPool<T>*)args;
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();
            while (tp->tasks_.size() == 0)
            {
                tp->Sleep();
            }
            T t = tp->tasks_.front();
            tp->tasks_.pop();
            tp->Unlock();
            t();

        }
    }

    void Start()
    {
        for (int i = 0; i < threadpool.size(); i++)
        {
            pthread_create(&(threadpool[i].tid), nullptr, handler, this);
            threadpool[i].name = "thread-" + std::to_string(i);
        }
    }

    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }
    void Push(const T& t)
    {
        Lock();
        tasks_.push(t);
        Wake();
        Unlock();
    }

private:
    std::vector<ThreadInfo> threadpool;
    std::queue<T> tasks_;

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;

};